package com.zenagro.servlets;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.zenagro.utils.FileEntityUtils;

public class DownloadServlet extends HttpServlet {


    protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String [] uri = request.getRequestURI().split("/");
        

         String model=uri[3];
         String id=uri[4];
         String fileName = uri[5];
         String fileType = "application/pdf";
         // Find this file id in database to get file name, and file type

         // You must tell the browser the file type you are going to send
         // for example application/pdf, text/plain, text/html, image/jpg
         response.setContentType(fileType);

         // Make sure to show the download dialog
         response.setHeader("Content-disposition","attachment; filename="+fileName);

         // Assume file name is retrieved from database
         // For example D:\\file\\test.pdf
         
         File my_file = new File(FileEntityUtils.pathRepo+File.separator+model+File.separator+id+File.separator+fileName);

         // This should send the file to browser
         OutputStream out = response.getOutputStream();
         FileInputStream in = new FileInputStream(my_file);
         
         byte[] buffer = new byte[4096];
         int length;
         while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
         }
         in.close();
         out.flush();
    }
}